//index.js
//获取应用实例
const app = getApp();
const config = app.globalData.config;
const util = app.globalData.util;
const QQMapWX = require('../../utils/qqmap-wx-jssdk.min.js');
const share = require('../../template/share/share.js')
Page({
  data: {
    isTop: true,
    active: 0,
    pageIndex: 1,
    pageSize: 7,
    homeList: [],
    activitys: [],
    location: {
      code: '',
      name: "不限区域"
    },
    isShowTips: true,
    endTimeList: [],
    countDownList: {},
    share: {
      isShow: false,
      index: 0,
      param: '{}'
    },
    userId: 0
  },
  onLoad: function(options) {
    var that = this;
    var userInfo = wx.getStorageSync('sUserInfo')
    if (!!userInfo) {
      that.setData({
        userId: userInfo.id
      })
    }
    //获取当前位置
    // wx.getLocation({
    //   type: 'gcj02',
    //   success(res) {
    //     const latitude = res.latitude;
    //     const longitude = res.longitude;
    //     that.mygetLocation(latitude, longitude);
    //   }
    // });
    that.getHomeList();
    // 执行倒计时函数
    that.countDown();
  },
  onShow: function() {
    this.getHomeList();
  },
  onPageScroll: function(e) {
    this.setData({
      isTop: e.scrollTop < 400
    });
  },
  onGoTop() {
    wx.pageScrollTo({
      scrollTop: 0
    })
  },
  /**
   * 获取首页数据
   */
  getHomeList() {
    var that = this;
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    wx.request({
      url: config.homeUrl,
      method: "GET",
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      data: {
        pageIndex: that.data.pageIndex,
        pageSize: that.data.pageSize,
        address: that.data.location.code,
        userId: that.data.userId
      },
      success: function(res) {
        // 回调函数
        var moment_list = that.data.homeList;
        for (var i = 0; i < res.data.data.length; i++) {
          moment_list.push(res.data.data[i]);
        }
        var endTimeList = moment_list.map(x => ({
          id: x.id,
          time: x.openTime
        }));
        // 设置数据
        res.data && that.setData({
          homeList: moment_list,
          isShowTips: res.data.data.length == 0 || res.data.data.length < that.data.pageSize,
          endTimeList: endTimeList
        })
      },
      fail(res) {},
      complete(res) {
        wx.hideLoading();
        wx.stopPullDownRefresh();
      }
    })
  },
  getActivityList() {
    var that = this;
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    wx.request({
      url: config.activityListUrl,
      method: "GET",
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      data: {
        pageIndex: this.data.pageIndex,
        pageSize: this.data.pageSize,
      },
      success: function(resp) {
        if (resp.data.code == "200") {
          that.setData({
            activitys: resp.data.data
          })
        }
      },
      fail(res) {},
      complete(res) {
        wx.hideLoading();
      }
    })
  },
  /**
   * 获取定位的详细信息
   */
  mygetLocation: function(latitude, longitude) {
    var that = this;
    var qqmapsdk = new QQMapWX({
      key: config.qqmapKey
    });
    qqmapsdk.reverseGeocoder({
      location: {
        latitude,
        longitude
      },
      success: function(res) {
        var res = res.result;
        that.setData({
          location: {
            code: res.ad_info.adcode,
            name: res.ad_info.district
          }
        })
        that.getHomeList();
      },
      fail: function(error) {
        console.error(error);
      }
    })
  },
  /**
   * 选择地址
   */
  onChooseLocation: function() {
    var that = this;
    wx.chooseLocation({
      success: res => {
        const latitude = res.latitude;
        const longitude = res.longitude;
        that.setData({
          homeList: []
        })
        that.mygetLocation(latitude, longitude);
      }
    })
  },
  /**
   * 分享
   */
  onShareAppMessage(res) {
    let that = this;
    return {
      title: '活动指南', // 转发后 所显示的title
      path: '/pages/index/index', // 相对的路径
      success: (res) => { // 成功后要做的事情
        wx.getShareInfo({
          shareTicket: res.shareTickets[0],
          success: (res) => {
            console.log(res)
          },
          fail: function(res) {
            console.log(res)
          },
          complete: function(res) {
            console.log(res)
          }
        })
      },
      fail: function(res) {
        // 分享失败
        console.log(res)
      }
    }
  },
  /**
   * Tab切换
   */
  onClickTab(event) {
    var tab = event.currentTarget.dataset;
    var a = tab.tabindex * 1;
    if (a === 1) {
      wx.navigateTo({
        url: '/pages/initiate/initiate'
      })
    } else if (a === 2) {
      wx.redirectTo({
        url: '/pages/me/me'
      })
    }
  },
  /**
   * 下拉刷新
   */
  onPullDownRefresh() {
    this.setData({
      pageIndex: 1,
      homeList: [],
      location: {
        code: '',
        name: "不限区域"
      },
    })
    this.getHomeList();
  },
  /**
   * 上拉加载
   */
  onReachBottom() {
    if (this.data.isShowTips) {
      return;
    }
    var page = this.data.pageIndex + 1;
    this.setData({
      pageIndex: page
    })
    this.getHomeList();
  },
  /**
   * 倒计时函数
   */
  countDown() {
    // 获取当前时间，同时得到活动结束时间数组
    let newTime = new Date().getTime();
    let endTimeList = this.data.endTimeList;
    let countDownArr = {};

    // 对结束时间进行处理渲染到页面
    endTimeList.forEach(o => {
      let endTime = new Date(o.time).getTime();
      let obj = null;
      // 如果活动未结束，对时间进行处理
      if (endTime - newTime > 0) {
        let time = (endTime - newTime) / 1000;
        // 获取天、时、分、秒
        let day = parseInt(time / (60 * 60 * 24));
        let hou = parseInt(time % (60 * 60 * 24) / 3600);
        let min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
        let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
        obj = {
          day: util.formatNumber(day),
          hou: util.formatNumber(hou),
          min: util.formatNumber(min),
          sec: util.formatNumber(sec)
        }
      } else { //活动已结束，全部设置为'00'
        obj = {
          day: '00',
          hou: '00',
          min: '00',
          sec: '00'
        }
      }
      countDownArr[o.id] = obj;
    })
    // 渲染，然后每隔一秒执行一次倒计时函数
    this.setData({
      countDownList: countDownArr
    })
    setTimeout(this.countDown, 1000);
  },
  /**
   * 推荐
   */
  onHigh() {
    var that = this;
    var userInfo = wx.getStorageSync('sUserInfo');
    if (!userInfo) {
      wx.navigateTo({
        url: '/pages/high/high'
      })
      wx.showToast({
        title: '请授权',
        icon: 'none'
      })
    } else {
      wx.request({
        url: config.canPushUrl,
        method: "GET",
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        data: {
          userId: userInfo.id
        },
        success: function(resp) {
          if (resp.data.code == "200") {
            switch (resp.data.data) {
              case 0:
                wx.navigateTo({
                  url: '/pages/high/high?buy=1'
                })
                wx.showToast({
                  title: '今日推荐位已售完',
                  icon: 'none',
                  duration: 3000
                })
                break;
              case 1:
                wx.navigateTo({
                  url: '/pages/initiate/initiate?high=1',
                })
                break;
              case 2:
                wx.navigateTo({
                  url: '/pages/high/high'
                })
                break;
            }
          }
        },
        fail(res) {},
        complete(res) {
          wx.hideLoading();
        }
      })
    }
  },
  //分享相关
  onCloseShare: share.onCloseShare,
  onShowShare: share.onShowShare,
  onSelectShare: share.onSelectShare
})